<?php

namespace app\admin\model;

use think\Model;


class CategoryProduct extends Model
{




    // 表名
    protected $name = 'category_product';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text'
    ];


    protected static function init()
    {
//        self::afterInsert(function ($row) {
//            $pk = $row->getPk();
//            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
//        });
    }





    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function productCate(){
        return $this->belongsTo('CategoryProduct', 'pid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 返回商品分类树列表
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public function getCategoryProductLists()
    {
        $result=[];
        $list=$this->where(["status"=>1])->order("id","asc")->field(["id","pid","name"])->select();
        $result=$list;

        return $result;
    }



}
